﻿(function (module) {
    var utilities = function ($q, $timeout, $log, $http) {

        var svc = {
            //asClientId: function (aggregateId) {
            //    var first = aggregateId.indexOf('/');
            //    var last = aggregateId.lastIndexOf('/');

            //    var clientId = aggregateId.substring(0, first) + '|' + aggregateId.substring(last + 1);

            //    return clientId;
            //},

            asClientIdentifier: function (aggregateId) {

                var first = aggregateId.indexOf('/');
                var last = aggregateId.lastIndexOf('/');

                var clientId = {
                    collection: aggregateId.substring(0, first),
                    id: aggregateId.substring(last + 1),
                    tenantId: aggregateId.substring(first + 1, last )
                };

                return clientId;
            },

            _ids: [],
            _checkIds: function () {
                var self = this;
                if (self._ids.length < 25) {
                    $log.debug('ids are less than 25.');
                    self._getNextIdsChunk()
                        .then(function (data) {
                            $log.debug('ids returned from the server.');
                            self._ids = self._ids.concat(data);
                            //$log.debug('New ids:', self._ids);
                        });
                }
            },
            _getNextIdsChunk: function (qty) {

                $log.debug('backendServices._getNextIdsChunk(qty)', qty);

                if (!qty) {
                    qty = 50;
                }

                var deferred = $q.defer();

                var uri = '/api/backend/generateIdentifiers?qty=' + qty;

                $log.debug('_getNextIdsChunk: [uri]', uri);

                $http.get(uri)
                    .success(function (data, status, headers, config) {
                        $log.debug('_getNextIdsChunk executed:', data, status, headers, config);
                        deferred.resolve(data);
                    });

                $log.debug('server called, waiting for the promise.');

                return deferred.promise;
            },
            getIdentifier: function () {

                var self = this;

                if (self._ids.length == 0) {
                    throw "Not supported exception, still getting ids from the server";
                }

                var uuid = self._ids.pop();
                self._checkIds();

                return uuid;
            },

            //generateIdentifier: function () {
            //    var d = new Date().getTime();
            //    var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            //        var r = (d + Math.random() * 16) % 16 | 0;
            //        d = Math.floor(d / 16);
            //        return (c == 'x' ? r : (r & 0x7 | 0x8)).toString(16);
            //    });
            //    return uuid;
            //},

            isSuccessStatus: function (status) {
                return status >= 200 && status <= 299;
            } //,

            //isArray: function (obj) {
            //    return obj.constructor == Array;
            //}
        };

        svc._checkIds();

        return svc;
    };
    utilities.$inject = ['$q', '$timeout', '$log', '$http'];

    module.factory('utilities', utilities);

}(angular.module('global.services')));